import random
import time
import requests
from requests.adapters import HTTPAdapter
from tenacity import retry, stop_after_attempt, wait_random
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 发送请求获取代理列表
response = requests.get(
    "http://api.xiequ.cn/VAD/GetIp.aspx?act=get&uid=146487&vkey=FF9B14700D36FA974A3F5C301DFB4DD9&num=100&time=30&plat=0&re=0&type=0&so=1&ow=1&spl=1&addr=&db=1")
proxy_data = response.json()

# 检查响应是否成功
if proxy_data["code"] == 0:
    # 从 JSON 数据中提取代理列表
    proxy_list = proxy_data['data']
    print(proxy_list)
    # 将代理列表转换为可以被 `requests` 使用的格式
    proxies = [{"HTTPS": f"HTTP://{proxy['IP']}:{proxy['Port']}"} for proxy in proxy_list] + \
              [{"HTTP": f"HTTP://{proxy['IP']}:{proxy['Port']}"} for proxy in proxy_list]
    print(proxies)

    @retry(stop=stop_after_attempt(10), wait=wait_random(min=1, max=6))
    def getUrl(url, headers, proxy):
        js = None
        try:
            sess = requests.Session()
            sess.mount('HTTP://', HTTPAdapter(max_retries=3))
            sess.mount('HTTPS://', HTTPAdapter(max_retries=3))
            sess.keep_alive = False  # 关闭多余连接

            response = requests.get(url, headers=headers, timeout=(5, 5), stream=True, proxies=proxy, verify=False)
            response.raise_for_status()
            js = response.json()
            for data in js['data']['list']:
                with open('video_url2.csv', 'a+', encoding='utf-8') as f:
                    f.write(f"{data['short_link_v2']}\n")
            print(f'爬取每周必看第{i}周完成')
            response.close()
            time.sleep(random.uniform(1, 3))
        except Exception as e:
            print(js)
            print(f'请求错误: {e}')
            time.sleep(random.uniform(1, 3))
            raise


    if __name__ == '__main__':
        with open('video_url1.csv', 'w', encoding='utf-8') as f:
            f.write('videoUrl\n')

        USER_AGENTS = [
            "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
            "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0',
        ]

        headers = {'User-Agent': random.choice(USER_AGENTS),
                   "cookie": "buvid4=57A97A34-D340-4062-7982-AB0703FE2BD978059-022051114-mM8SV6RauEz6PpLrEBc1Sg%3D%3D; CURRENT_BLACKGAP=0; LIVE_BUVID=AUTO3616523641952351; is-2022-channel=1; header_theme_version=CLOSE; hit-new-style-dyn=1; DedeUserID=365769122; DedeUserID__ckMd5=f552ad8f9642a996; enable_web_push=DISABLE; rpdid=|(k|k)kR~mkR0J'u~|JklJ)R); FEED_LIVE_VERSION=V_WATCHLATER_PIP_WINDOW3; _uuid=9C1022378-1DF2-5954-9A7E-72491D6FC54979973infoc; SESSDATA=ab4349d7%2C1731392484%2C72b4e%2A51CjAnrrndoR5W2iSH2i5rddxjHqjB_IeBmNhmkOeK67ONod3rR44gF5d8ybJDETnWB0wSVjhKOUFfRFpfYkpGYkZucGN1MUNnVjFMN0JQWjlRNUtiQzlnMEFfUzBTaUpJSWVVOTdzaDdnV3ZZMFQ2MkRmQ0JGZEZNOHRYSEFiQTRySktRTkh5YUF3IIEC; bili_jct=4c2cf746da94f22bbd950018a2fbd85a; PVID=1; hit-dyn-v2=1; CURRENT_QUALITY=80; buvid3=EDE38C36-02DB-4B28-0F99-13A8EE9081E596995infoc; b_nut=1718415698; buvid_fp=fde07cbd3f19a92c31ad85249b906000; CURRENT_FNVAL=4048; fingerprint=9e3d5887a7946d3aad1dd9cbadd97e98; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MjM4MDMzNjYsImlhdCI6MTcyMzU0NDEwNiwicGx0IjotMX0.CnTdFuw3reifJqi06vKtSqpSaamKse6-JaLl-9tvoJY; bili_ticket_expires=1723803306; bp_t_offset_365769122=965162701410009088; home_feed_column=4; sid=8jkqrpfo; browser_resolution=825-632; b_lsid=5847838A_19150453E15",
                   'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'
                   }

        for i in range(1, 282):
            URL = [
                f"https://api.bilibili.com/x/web-interface/popular/series/one?number={i}&web_location=334.933&w_rid=ed96e09ecb27734929026a712a3abf2a&wts=9724478909",
                f'https://api.bilibili.com/x/web-interface/popular/series/one?number={i}&web_location=333.933&w_rid=ed96e09ecb27734929026a712a3abf2a&wts=9723378909',
                f'https://api.bilibili.com/x/web-interface/popular/series/one?number={i}&web_location=334.633&w_rid=dd96e09ecb23734929026a712a3abf2a&wts=9724478999',
                f'https://api.bilibili.com/x/web-interface/popular/series/one?number={i}&web_location=344.733&w_rid=dd96e09ecb23734929026a712a3abf2a&wts=9722478999',
                f'https://api.bilibili.com/x/web-interface/popular/series/one?number={i}&web_location=334.433&w_rid=dd96e09ecb23734929024a712a3abf2a&wts=9724428999',
            ]
            url = random.choice(URL)  # 随机使用api
            proxy = proxies[i % len(proxies)]  # 循环使用代理
            try:
                getUrl(url, headers, proxy)
                time.sleep(random.uniform(1, 3))
            except Exception as e:
                print(f'最终重试失败: {e}')

else:
    print("未能成功获取代理列表。请检查 API 调用是否正确。")
